package com.example.sandbox.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.*;

@Component
@Slf4j
public class PayUtil {

    private final String uuPayUrl = "https://pay-india.ssonicpay.com";


    private final Random random = new Random();
    private final double successProbability = 0.5; // 50% 的成功概率

    ScheduledThreadPoolExecutor scheduledThreadPoolExecutorPay = new ScheduledThreadPoolExecutor(100);
    ScheduledThreadPoolExecutor scheduledThreadPoolExecutorRefund = new ScheduledThreadPoolExecutor(100);
    ScheduledThreadPoolExecutor scheduledThreadPoolExecutorTransfer = new ScheduledThreadPoolExecutor(100);

    public void doNotifyPay(String ifCode, String wayCode, String txid) {
        scheduledThreadPoolExecutorPay.schedule(() -> {
            // 执行推送
            try {
                notifyPaymentPay(ifCode, wayCode, txid);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }, 1, TimeUnit.SECONDS);
    }

    public void doNotifyRefund(String ifCode, String wayCode, String txid) {
        scheduledThreadPoolExecutorRefund.schedule(() -> {
            // 执行推送
            try {
                notifyPaymentRefund(ifCode, wayCode, txid);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }, 1, TimeUnit.SECONDS);
    }


    public void notifyPaymentPay(String ifCode, String wayCode, String payOrderId) throws IOException {
        boolean isSuccess = random.nextDouble() < successProbability;
        String url = "";
        // 构建请求体参数
        Map<String, Object> params = new HashMap<>();
//                if (isSuccess){
//                    url = String.format("http://192.168.50.145:27003/api/pay/notify/%s/%s", ifCode, wayCode);
//                }else {
//                    url = String.format("http://192.168.50.48:27003/api/pay/notify/%s/%s", ifCode, wayCode);
//                }
        url = String.format(uuPayUrl + "/api/pay/notify/%s/%s", ifCode, wayCode);

        params.put("external_id", "b1681fe6931c4ff8a57c775d6fee4387");
        params.put("txid", payOrderId);
        params.put("debtor_document_number", null);
        params.put("debtor_name", null);
        params.put("amount", "1000.0"); // 示例金额
        params.put("status", "PAID");
        params.put("payer_request", null);
        params.put("additional_information", new Object[]{}); // 空数组
        params.put("qr_code", "00020101021226810014br.gov.bcb.pix2559api-h.fakebank.com.br/api/cob/b1681fe6931c4ff8a57c775d6fee43875204000053039865802BR5913SUPERPAGAMENTOS LTDA6009SAO PAULO62070503***630442F4");
        params.put("qr_code_image_url", "https://api-h.wudi-pay.codesign.ag/qr_code/WD1727231601932M1724118185RS75L");
        params.put("expires_at", "2024-09-25T02:46:09.000000Z");
        params.put("provider", "FAKE_BANK");
        params.put("provider_account", "1");
        params.put("fee", 0.01);
        params.put("account_id", 74);
        params.put("workspace_id", 34);
        params.put("updated_at", "2024-09-25T02:36:09.000000Z");
        params.put("created_at", "2024-09-25T02:36:09.000000Z");
        params.put("id", 130033);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost request = new HttpPost(url);

            // 将参数转换为 JSON 字符串
            String json = new ObjectMapper().writeValueAsString(params);
            StringEntity entity = new StringEntity(json);
            entity.setContentType("application/json");
            request.setEntity(entity);


            // 读取请求体
            // 生成 HMAC SHA256 签名
            String hmacsha256Signature = generateHMACSHA256Signature(json, "123456789");
            request.setHeader("Signature", hmacsha256Signature);

            HttpResponse response = httpClient.execute(request);

        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    public void notifyPaymentRefund(String ifCode, String wayCode, String payOrderId) throws IOException {
        boolean isSuccess = random.nextDouble() < successProbability;

        String url = String.format(uuPayUrl + "/api/pay/notify/%s/%s", ifCode, wayCode);
        // 构建请求体参数
        Map<String, Object> params = new HashMap<>();

        // 从提供的 JSON 中提取参数
        params.put("provider_account", "1");
        params.put("amount", 2);
        params.put("fee", 0.01);
        params.put("txid", payOrderId);
        params.put("qr_code_image_url", "https://api-h.wudi-pay.codesign.ag/qr_code/WD1727145617836M1727076029RTMBU");
        params.put("created_at", "2024-09-24T02:40:18.000000Z");
        params.put("webhook_status", "succeed");
        params.put("external_id", "e5bbde1729104478a7307458ca3be1f5");

        // 组装 refunds 数组
        List<Map<String, Object>> refunds = new ArrayList<>();
        Map<String, Object> refund = new HashMap<>();
        refund.put("performed_at", "2024-09-25T08:37:50.000000Z");
        refund.put("provider_account", "1");
        refund.put("amount", 2);
        refund.put("created_at", "2024-09-25T08:37:47.000000Z");
        refund.put("external_id", "699ad81f-70eb-433c-b469-d45237fbeff8");
        refund.put("uuid", "55cd94d3-ed35-48e5-8b5e-3a9c6d6e28a9");
        refund.put("workspace_id", 34);
        refund.put("account_id", 74);
        refund.put("updated_at", "2024-09-25T08:37:52.000000Z");
        refund.put("provider", "FAKE_BANK");
        refund.put("charge_id", 129991);
        refund.put("end_to_end_id", "D12345678202409250837eFYKNjhM4Xp");
        refund.put("correlation_id", "R1838860326572707841");
        refund.put("id", 111);
        refund.put("status", "DONE");

        refunds.add(refund);
        params.put("refunds", refunds);

        params.put("paid_at", "2024-09-24T02:40:25.000000Z");
        params.put("workspace_id", 34);
        params.put("additional_information", new ArrayList<>()); // 空数组
        params.put("expires_at", "2024-09-24T02:50:18.000000Z");
        params.put("account_id", 74);
        params.put("updated_at", "2024-09-25T08:37:52.000000Z");
        params.put("provider", "FAKE_BANK");
        params.put("qr_code", "00020101021226810014br.gov.bcb.pix2559api-h.fakebank.com.br/api/cob/e5bbde1729104478a7307458ca3be1f55204000053039865802BR5913SUPERPAGAMENTOS LTDA6009SAO PAULO62070503***630442F4");
        params.put("id", 129991);
        params.put("status", "DONE");

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost request = new HttpPost(url);

            // 将参数转换为 JSON 字符串
            String json = new ObjectMapper().writeValueAsString(params);
            StringEntity entity = new StringEntity(json);
            entity.setContentType("application/json");
            request.setEntity(entity);


            // 读取请求体
            // 生成 HMAC SHA256 签名
            String hmacsha256Signature = generateHMACSHA256Signature(json, "123456789");
            request.setHeader("Signature", hmacsha256Signature);

            HttpResponse response = httpClient.execute(request);

        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }



    public void doNotifyTransfer(String ifCode, String wayCode, String txid) {
        scheduledThreadPoolExecutorTransfer.schedule(() -> {
            // 执行推送
            try {
                notifyPaymentTransfer(ifCode, wayCode, txid);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }, 1, TimeUnit.SECONDS);
    }
    public void notifyPaymentTransfer(String ifCode, String wayCode, String payOrderId) throws IOException {
//        boolean isSuccess = random.nextDouble() < successProbability;

        String url = String.format(uuPayUrl + "/api/transfer/notify/%s/%s", ifCode, wayCode);
        // 构建请求体参数
        Map<String, Object> params = new HashMap<>();
        params.put("performed_at", "2024-10-15T01:32:17.000000Z");
        params.put("addressing_key", "35186778885");
        params.put("reason", "Pix key search has failed");
        params.put("provider_account", "11");
        params.put("recipient_document_number", "35186778885");
        params.put("fee", 0.05);
        params.put("created_at", "2024-10-15T01:32:17.000000Z");
        params.put("uuid", "69cc1a30-3fc7-44e7-90ed-11a68af9edcc");
        params.put("addressing_key_type", "CPF");
        params.put("workspace_id", 67);
        params.put("initialization_type", "DICT");
        params.put("updated_at", "2024-10-15T01:32:17.000000Z");
        params.put("provider", "DOCK");
        params.put("id", 12169671);
        params.put("amount", 500);
        params.put("account_id", 398);
        params.put("correlation_id", payOrderId);
        params.put("error_code", "OUT002");

        // 添加 account 对象中的键值对
        Map<String, Object> account = new HashMap<>();
        account.put("workspace_id", 67);
        account.put("updated_at", "2024-10-03T16:02:06.000000Z");
        account.put("name", "Default");
        account.put("deny_legal_entities_cash_outs", true);
        account.put("created_at", "2024-06-13T00:59:45.000000Z");
        account.put("id", 398);
        account.put("customer_id", 299);
        account.put("plan_id", 497);
        account.put("status", "DONE");

        // 将 account 添加到 params 中
        params.put("account", account);
        params.put("status", "DONE");

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost request = new HttpPost(url);

            // 将参数转换为 JSON 字符串
            String json = new ObjectMapper().writeValueAsString(params);
            StringEntity entity = new StringEntity(json);
            entity.setContentType("application/json");
            request.setEntity(entity);


            // 读取请求体
            // 生成 HMAC SHA256 签名
            String hmacsha256Signature = generateHMACSHA256Signature(json, "123456789");
            request.setHeader("Signature", hmacsha256Signature);

            HttpResponse response = httpClient.execute(request);

        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    public static String generateHMACSHA256Signature(String data, String secret)
            throws NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        mac.init(secretKeySpec);

        byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));

        // 将字节数组转换为十六进制字符串
        StringBuilder sb = new StringBuilder(2 * rawHmac.length);
        for (byte b : rawHmac) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
